package com.jeecg.demo.controller;

import com.jeecg.demo.entity.SysRoleEntity;
import com.jeecg.demo.entity.SysUserEntity;
import com.jeecg.demo.entity.TraderEntity;
import com.jeecg.demo.service.SysUserServiceI;
import com.jeecg.demo.util.PopupDataBindUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: SYS_USER
 * @author onlineGenerator
 * @date 2018-11-15 13:42:49
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/sysUserController")
public class SysUserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserServiceI sysUserService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private PopupDataBindUtil bindUtil;


    /**
     * SYS_USER列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, String type) {

        if ("info".equals(type)) {
            request.setAttribute("title", "交易商查询");
        }
        else if ("frozen".equals(type)) {
            request.setAttribute("title", "交易商冻结解冻");
        }
        else if ("logoff".equals(type)) {
            request.setAttribute("title", "交易商注销");
        }
        else if ("pwdreset".equals(type)) {
            request.setAttribute("title", "交易商密码重置");
        }

        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/sysUser/sysUserList");
    }

    @RequestMapping(params = "lists")
    public ModelAndView lists(HttpServletRequest request, String type) {

        if ("infos".equals(type)) {
            request.setAttribute("title", "交易商查询");
        }
        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/sysUser/sysUserList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(SysUserEntity sysUser, HttpServletRequest request,
            HttpServletResponse response, DataGrid dataGrid, String type)
            throws Exception {
        CriteriaQuery cq = new CriteriaQuery(SysUserEntity.class, dataGrid);
        // 查询条件组装器
        // 如果绑定报表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
        dataGrid.setSort(dataGrid.getSort().replace("roleidDicName", "roleid"));
        dataGrid.setSort(dataGrid.getSort().replace("orgidDicName", "orgid"));
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                sysUser, request.getParameterMap());
        try {

        	String fullname = request.getParameter("orgidDicName");
            if (StringUtils.isNotEmpty(fullname)) {
    			//List<TraderEntity> list = systemService.findByProperty(TraderEntity.class, "fullname", fullname);
                List<TraderEntity> list = systemService.findHql(" from TraderEntity where  fullname like ? ", "%" + fullname + "%");
    			if (list.size()>0) {
    				Integer[] traderidArr = new Integer[list.size()];
    				for (int j = 0; j < list.size(); j++) {
    					Integer traderid = list.get(j).getTraderid();
    					traderidArr[j]=traderid;
    				}
    				cq.in("orgid", traderidArr);
    				cq.add();
    			}else{
    				cq.eq("orgid", -1);
    				cq.add();
    			}
    		}

            // 自定义追加查询条件
            if ("manager".equals(type)) {
                cq.eq("usertype", "1");
                cq.add();
            }
            else {
                cq.eq("usertype", "3");
                cq.add();
            }
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.sysUserService.getDataGridReturn(cq, true);

        // 绑定报表数据
        bindUtil.BindReportFieldNameDataGrid(SysUserEntity.class, dataGrid,
                "roleid", "rolename");
        bindUtil.BindReportFieldNameDataGrid(SysUserEntity.class, dataGrid,
                "orgid", "fullname");

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        sysUser = systemService.getEntity(SysUserEntity.class, sysUser.getId());
        message = "删除成功";
        try {
            sysUserService.delete(sysUser);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                SysUserEntity sysUser = systemService.getEntity(
                        SysUserEntity.class, Integer.parseInt(id));
                sysUserService.delete(sysUser);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
            sysUser.setPassword("E780A11E3B3D86BB4BE93B6DBF885196");
            sysUserService.save(sysUser);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(sysUser, t);
            sysUserService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 冻结SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doFrozen")
    @ResponseBody
    public AjaxJson doFrozen(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "冻结成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser
                .getId());
        try {
            t.setUserverifystatus("4");
            sysUserService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "冻结失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 解冻SYS_USER
     * @return
     */
    @RequestMapping(params = "doThaw")
    @ResponseBody
    public AjaxJson doThaw(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "解冻成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser
                .getId());
        if (!t.getUserverifystatus().equals("3")) {
            try {
                t.setUserverifystatus("3");
                sysUserService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE,
                        Globals.Log_Leavel_INFO);
                //删除  t_s_user_login_log
                systemService.executeSql("delete from t_s_user_login_log l where l.username=? and l.logintype = 1 and l.operatetype = 0", t.getLoginname());
            }
            catch (Exception e) {
                e.printStackTrace();
                message = "解冻失败";
                throw new BusinessException(e.getMessage());
            }
            j.setMsg(message);
            return j;
        }
        else {
            message = "无法解冻正常状态的用户";
            j.setMsg(message);
            return j;
        }
    }

    /**
     * 注销SYS_USER
     * @return
     */
    @RequestMapping(params = "doLogoff")
    @ResponseBody
    public AjaxJson doLogoff(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "注销成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser
                .getId());
        try {
            t.setUserverifystatus("5");
            sysUserService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "注销失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 恢复SYS_USER
     * @return
     */
    @RequestMapping(params = "doLogreset")
    @ResponseBody
    public AjaxJson doLogreset(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "恢复成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser
                .getId());
        if (!t.getUserverifystatus().equals("3")) {
            try {
                t.setUserverifystatus("3");
                sysUserService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE,
                        Globals.Log_Leavel_INFO);
            }
            catch (Exception e) {
                e.printStackTrace();
                message = "恢复失败";
                throw new BusinessException(e.getMessage());
            }
            j.setMsg(message);
            return j;
        }
        else {
            message = "无法恢复正常状态用户";
            j.setMsg(message);
            return j;
        }
    }

    /**
     * 密码重置SYS_USER
     *
     * @return
     */
    @RequestMapping(params = "doPwdreset")
    @ResponseBody
    public AjaxJson doPwdreset(SysUserEntity sysUser, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "密码重置成功";
        SysUserEntity t = sysUserService.get(SysUserEntity.class, sysUser
                .getId());
        try {
            t.setPassword("E780A11E3B3D86BB4BE93B6DBF885196");
            sysUserService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "密码重置失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * SYS_USER新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser.getId());
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-add");
    }

    /**
     * SYS_USER编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser
                    .getId());
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	if(entity!=null){
            		rolename += entity.getRolename()+",";
            	}

			}
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            if(entity!=null){
            	   String fullname = entity.getFullname();
                   req.setAttribute("fullname", fullname);
            }
            req.setAttribute("sysUserPage", sysUser);
            req.setAttribute("rolename", rolename);
            req.setAttribute("action", "sysUserController.do?doUpdate");
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * SYS_USER冻结页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goFrozen")
    public ModelAndView goFrozen(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser
                    .getId());
            req.setAttribute("action", "sysUserController.do?doFrozen");
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * SYS_USER解冻页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goThaw")
    public ModelAndView goVerify(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser
                    .getId());
            req.setAttribute("action", "sysUserController.do?doThaw");
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * SYS_USER注销页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goLogoff")
    public ModelAndView goLogoff(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser
                    .getId());
            req.setAttribute("action", "sysUserController.do?doLogoff");
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * SYS_USER恢复页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goLogreset")
    public ModelAndView goLogreset(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser
                    .getId());
            req.setAttribute("action", "sysUserController.do?doLogreset");
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * SYS_USER密码重置页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goPwdreset")
    public ModelAndView goPwdreset(SysUserEntity sysUser, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(sysUser.getId())) {
            sysUser = sysUserService.getEntity(SysUserEntity.class, sysUser.getId());
            System.out.println(sysUser + "-------------------------------------------------------------");
            req.setAttribute("action", "sysUserController.do?doPwdreset");
            String[] split = sysUser.getRoleid().split(",");
            String rolename = "";
            for (String string : split) {
            	SysRoleEntity entity = systemService.getEntity(SysRoleEntity.class, Integer.valueOf(string));
            	rolename += entity.getRolename()+",";
			}
            req.setAttribute("rolename", rolename);
            TraderEntity entity = systemService.getEntity(TraderEntity.class, sysUser.getOrgid());
            String fullname = entity.getFullname();
            req.setAttribute("fullname", fullname);
            req.setAttribute("sysUserPage", sysUser);
        }
        return new ModelAndView("com/jeecg/sysUser/sysUser-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "sysUserController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(SysUserEntity sysUser, HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap,String ids) {
        CriteriaQuery cq = new CriteriaQuery(SysUserEntity.class, dataGrid);
        cq.eq("usertype", "3");
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, sysUser, request.getParameterMap());
        cq.in("id", bindUtil.idsToIntegerArray(ids));
        cq.add();
        List<SysUserEntity> sysUsers = this.sysUserService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "交易商查询");
        modelMap.put(NormalExcelConstants.CLASS, SysUserEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("交易商查询", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, sysUsers);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(SysUserEntity sysUser, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "SYSUSER");
        modelMap.put(NormalExcelConstants.CLASS, SysUserEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("SYSUSER列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request,HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUserEntity> listSysUserEntitys = ExcelImportUtil.importExcel(file.getInputStream(), SysUserEntity.class, params);
                for (SysUserEntity sysUser : listSysUserEntitys) {
                    sysUserService.save(sysUser);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

}
